package com.yanqu.road.dao.impl.channelcenter.washe;

import com.yanqu.road.dao.cache.SqlCacheParam;
import com.yanqu.road.dao.impl.TempNoPoolCacheDao;
import com.yanqu.road.entity.activity.washe.config.WasheBoxConfig;
import com.yanqu.road.entity.activity.washe.config.WasheConfig;
import com.yanqu.road.entity.enums.washe.eWasheFunction;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TempWasheBoxConfigDaoImpl extends TempNoPoolCacheDao {

    public TempWasheBoxConfigDaoImpl(String dbParam) {
        super(dbParam);
    }

    private static String getWasheBoxConfigSql = "select * from `t_n_washepvp_box` where `activityId`=? and ( `seasonId`<=? or `seasonId`=? )";

    public Map<Integer, List<WasheBoxConfig>> getWasheBoxConfigListMap(int activityId, int seasonId, int version) {

        SqlCacheParam sqlCacheParam = getCacheParam(getWasheBoxConfigSql);
        sqlCacheParam.addParam(Integer.class, activityId);
        sqlCacheParam.addParam(Integer.class, WasheConfig.SEASON_ID_NULL);
        sqlCacheParam.addParam(Integer.class, seasonId);
        // 先取缓存
        Object cacheResult = getCacheResult(sqlCacheParam);
        if (cacheResult != null) {
            return (Map<Integer, List<WasheBoxConfig>>) cacheResult;
        }

        Map<Integer, List<WasheBoxConfig>> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            call = createCall(sqlCacheParam);
            rs = call.executeQuery();
            while (rs.next()) {
                WasheBoxConfig washeBoxConfig = new WasheBoxConfig();
                washeBoxConfig.setActivityId(rs.getInt("activityId"));
                washeBoxConfig.setBoxId(rs.getInt("boxId"));
                washeBoxConfig.setSeasonId(rs.getInt("seasonId"));
                washeBoxConfig.setQuality(rs.getInt("quality"));
                washeBoxConfig.setRewards(rs.getString("rewards"));
                washeBoxConfig.setNewrewards(rs.getString("newrewards"));

                String tmpParam = eWasheFunction.NewBoxConfig.isOpen(version) ? rs.getString("param") : "0";
                if (StringUtils.isNullOrEmpty(tmpParam) || "0".equals(tmpParam)) {
                    tmpParam = "0|9999999";
                }
                washeBoxConfig.setParam(tmpParam);

                washeBoxConfig.init(version);

                map.putIfAbsent(washeBoxConfig.getSeasonId(), new ArrayList<>());
                map.get(washeBoxConfig.getSeasonId()).add(washeBoxConfig);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeConnection(call, rs);
        }
        // 添加缓存
        addCacheResult(sqlCacheParam, map);
        return map;
    }

}
